package _type

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type UnixTime int64

func (t *UnixTime) Scan(value interface{}) error {
	if value == nil {
		*t = 0
		return nil
	}

	switch v := value.(type) {
	case time.Time:
		// 数据库驱动直接提供了 time.Time
		*t = UnixTime(v.Unix())
	case []byte:
		// MySQL 等驱动将 DATETIME 以字节切片形式返回
		str := string(v)
		// 根据数据库时间格式进行解析
		parsedTime, err := time.Parse("2006-01-02 15:04:05", str)
		if err != nil {
			return fmt.Errorf("parsing time from database: %w", err)
		}
		*t = UnixTime(parsedTime.Unix())
	case string:
		// 直接返回字符串
		parsedTime, err := time.Parse("2006-01-02 15:04:05", v)
		if err != nil {
			return fmt.Errorf("parsing time from database: %w", err)
		}
		*t = UnixTime(parsedTime.Unix())
	default:
		return fmt.Errorf("unsupported type for UnixTime: %T", value)
	}
	return nil
}

func (t UnixTime) Value() (driver.Value, error) {
	return time.Unix(int64(t), 0), nil
}
